<?php

namespace app\api\controller;

use Firebase\JWT\JWT;
use Think\Request;
use Think\Db;
use think\Controller;
use app\api\model\Result;
use app\model\AliSMS;
use app\model\Mail;
use think\facade\Session;
use think\Validate;

class UserController extends Controller
{
    /**
     * @var \think\Request Request实例
     */
    protected $request;
    protected $account_type;
    /**
     * 构造方法
     * @param Request $request Request对象
     * @access public
     */
    use Result;
    protected $param;
    protected $validate;
    protected $rule = [
        'login' => [
            'account' => 'require',
            'password' => 'require'
        ],
        'register' => [
            'nickname' => 'require',
            'account' => 'require|unique:member',
            'tu_code' => 'require|length:6',
            'repassword' => 'require',
            'password' => 'length:6,25|confirm:repassword'
        ],
        'find_pass' => [
            'account' => 'require',
            'repassword' => 'require',
            'password' => 'length:6,25|confirm:repassword',
            'tu_code' => 'length:6'
        ]
    ];

    public function __construct(Request $request)
    {


        if ($request->param('account')) {
            if (preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $request->param('account'))) {
                $this->account_type = 'email';
            }
            if (preg_match("/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/", $request->param('account'))) {
                $this->account_type = 'phone';
            }
            $this->param = $request->param();
        }
        parent::__construct();
        $this->validate = new Validate;
        $this->request = $request;
    }

    /**
     * 用户登录接口
     * @param phone  手机号
     * @param password  密码
     * @return [json]  状态码 错误信息 token
     */
    public function login()
    {
        $rule = $this->rule[__FUNCTION__];
        $validate = $this->validate;
        $validate = $validate->rule($rule);
        if (!$validate->check($this->param)) {
            $this->encode_json(40001, $validate->getError());
        }
        $user = Db::name('member')->where($this->account_type, $this->param['account'])->find();
        if (!empty($user)) {
            if ($user[$this->account_type] === $this->param['account'] && $user['pwd'] == md5($this->param['password'])) {

                $token = self::createJwt($user['member_id'], $user['level_id']);

                $this->encode_json(200, '登录成功', ['token' => $token]);
                dump($user);

            } else {
                $this->encode_json(10002, '账号密码错误');
            }
        } else {
            $this->encode_json(10002, '账户不存在');
        }
    }

    public function register()
    {
        $rule = $this->rule[__FUNCTION__];
        $validate = $this->validate;
        $rule[$this->account_type] = $rule['account'];
        unset($rule['account']);
        $this->param[$this->account_type] = $this->param['account'];
        unset($this->param['account']);
        $validate = $validate->rule($rule);
        if (!$validate->check($this->param)) {
            $this->encode_json(40001, $validate->getError());
        }
        if (!Session::has('code')) {
            $this->encode_json(40004, '请先发送验证吗!');
        }
        if (Session::get('code') !== $this->param['tu_code']) {
            $this->encode_json(40004, '验证码错误');
        }
        Session::delete('code');
        $member [$this->account_type] = $this->param[$this->account_type];
        $member ['pwd'] = md5($this->param['password']);
        $member ['nickname'] = $this->param['nickname'];
        $member ['last_ip'] = $_SERVER['REMOTE_ADDR'];
        $member ['last_time'] = time();
        $member ['level_id'] = time();
        $member ['add_time'] = time();
        $mem = Db::name('member')->insert($member);
        if ($mem) {
            $this->encode_json(10001, '注册成功  马上登陆');
        } else {
            $this->encode_json(40001, '系统繁忙稍后再试！');
        }
    }

    public function send_code()
    {
        $account = $this->request->param('account');
        /******** 判断账号是手机还是邮箱 **********/
        $code = str_shuffle(mt_rand(100000, 999999));
        session('code', $code);

        if (preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $account)) {
            /*****邮箱*****/
            $Mail = new Mail();
            $mail_state = $Mail->code($account, $code);
            if ($mail_state) {
                $this->encode_json(10001, '发送成功注意查收');
            } else {
                $this->encode_json(40001, '发送失败');
            }
        }
        if (preg_match("/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/", $account)) {
            /*****手机号*****/
            $Alisms = new AliSMS();
            $sms_state = $Alisms->send($account, 'changepass', ['code' => $code]);
            if ($sms_state) {
                $this->encode_json(10001, '发送成功注意查收');
            } else {
                $this->encode_json(40001, '发送失败');
            }
        }
    }

    public function find_pass()
    {
        $rule = $this->rule[__FUNCTION__];
        $validate = $this->validate;
        $rule[$this->account_type] = $rule['account'];
        unset($rule['account']);
        $this->param[$this->account_type] = $this->param['account'];
        unset($this->param['account']);
        $validate = $validate->rule($rule);
        if (!$validate->check($this->param)) {
            $this->encode_json(40001, $validate->getError());
        }
        if (!Session::has('code')) {
            $this->encode_json(40004, '请先发送验证码');
        }
        if (Session::get('code') !== $this->param['tu_code']) {
            $this->encode_json(40004, '验证码错误');
        }
        Session::delete('code');
        $res = Db::name('member')
            ->where($this->account_type, $this->param[$this->account_type])
            ->setField('pwd',md5($this->param['password']));
        if ($res) {
            $this->encode_json(10001, '重置密码成功');
        } else {
            $this->encode_json(10002, '重置密码失败');
        }
    }

    /**
     * 生成唯一token
     * @param int $userId 用户ID；
     * @return stirng         token
     */
    public function createJwt($userId, $level_id)
    {
        $key = md5('nobita'); //jwt的签发密钥，验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $time + 14400; //过期时间
        $token = array(
            "user_id" => $userId,
            "level_id" => $level_id,
            "iss" => "豌豆电商",//签发组织
            "aud" => "潘大老板", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = JWT::encode($token, $key);
        return $jwt;
    }
}

